<script setup lang="ts">
import type { Vehicle } from '#/api/vehicle';

import { computed, onMounted, ref } from 'vue';

import { MdiKeyboardEsc } from '@vben/icons';

import { ElForm, ElMessage, ElMessageBox } from 'element-plus';

import { deleteVehicleApi, getVehiclesApi, VehicleStatus } from '#/api/vehicle';

import VehicleFormDialog from './VehicleFormDialog.vue';

// 搜索表单数据
const searchForm = ref({
  licensePlate: '',
  status: undefined,
  brand: '',
  model: '',
  color: '',
  driverName: '',
});

// 表格数据和加载状态
const tableData = ref<Vehicle[]>([]);
const loading = ref(false);
const searchFormRef = ref<InstanceType<typeof ElForm>>();

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0,
  pageSizeOptions: [15, 20, 25, 30],
});

// 状态选项
const statusOptions = [
  { label: '可用', value: VehicleStatus.AVAILABLE },
  { label: '出车中', value: VehicleStatus.IN_USE },
  { label: '维保中', value: VehicleStatus.MAINTENANCE },
  { label: '停用', value: VehicleStatus.DISABLED },
];

// 弹框状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentVehicle = ref<null | Vehicle>(null);

// 弹框标题
const dialogTitle = computed(() => (isEdit.value ? '编辑车辆' : '新增车辆'));

// 状态标签类型映射
function getStatusType(status: VehicleStatus) {
  const statusMap: Record<VehicleStatus, string> = {
    [VehicleStatus.AVAILABLE]: 'success',
    [VehicleStatus.IN_USE]: 'warning',
    [VehicleStatus.MAINTENANCE]: 'info',
    [VehicleStatus.DISABLED]: 'danger',
  };
  return statusMap[status] || 'default';
}

// 查询数据
async function handleSearch() {
  try {
    loading.value = true;
    const params = { 
      ...searchForm.value,
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    };
    const response = await getVehiclesApi(params);
    tableData.value = response.list;
    pagination.value.total = response.total;
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    ElMessage.error('获取车辆列表失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 重置表单
function handleReset() {
  searchFormRef.value?.resetFields();
  // 筛选条件变更时，分页重置为第一页
  pagination.value.page = 1;
  handleSearch();
}

// 查询数据时的通用处理
function handleSearchWithReset() {
  // 筛选条件变更时，分页重置为第一页
  pagination.value.page = 1;
  handleSearch();
}

// 新增车辆
function handleAdd() {
  isEdit.value = false;
  currentVehicle.value = null;
  dialogVisible.value = true;
}

// 编辑车辆
function handleEdit(row: Vehicle) {
  isEdit.value = true;
  currentVehicle.value = { ...row };
  dialogVisible.value = true;
}

// 删除车辆
async function handleDelete(row: Vehicle) {
  if (
    row.status === VehicleStatus.IN_USE ||
    row.status === VehicleStatus.MAINTENANCE
  ) {
    ElMessage.warning(`当前车辆处于${row.status}状态，无法删除`);
    return;
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除该车辆吗？删除后数据不可恢复',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    );

    await deleteVehicleApi(row.vehicleId);
    ElMessage.success('删除成功');
    handleSearch();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除车辆失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  }
}

// 操作成功回调
function handleSuccess() {
  dialogVisible.value = false;
  handleSearch();
}

// 组件挂载后加载数据
onMounted(handleSearch);
</script>

<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 搜索表单 -->
    <el-card class="mb-3 rounded-xl border-0 shadow-lg">
      <ElForm
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input
                v-model="searchForm.licensePlate"
                placeholder="请输入车牌号"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="车辆状态" prop="status">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择车辆状态"
                clearable
                class="w-full"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="车辆品牌" prop="brand">
              <el-input
                v-model="searchForm.brand"
                placeholder="请输入车辆品牌"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="车辆型号" prop="model">
              <el-input
                v-model="searchForm.model"
                placeholder="请输入车辆型号"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="颜色" prop="color">
              <el-input
                v-model="searchForm.color"
                placeholder="请输入颜色"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="所属司机" prop="driverName">
              <el-input
                v-model="searchForm.driverName"
                placeholder="请输入司机姓名"
                clearable
                @keyup.enter="handleSearch"
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" class="size-15">
                查询
              </el-button>
              <el-button @click="handleReset" class="size-15"> 重置 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </ElForm>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="mb-3 rounded-xl border-0 shadow-lg">
      <div class="mb-6">
        <el-button
          type="primary"
          @click="handleAdd"
          class="size-20 rounded-lg px-6 py-2 shadow-md transition-shadow duration-200 hover:shadow-lg"
        >
          新增车辆
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        class="vehicle-table overflow-hidden rounded-lg"
        :header-cell-style="{
          background: '#f8fafc',
          color: '#374151',
          fontWeight: '600',
          borderBottom: '2px solid #e5e7eb',
        }"
        :cell-style="{ borderBottom: '1px solid #f1f5f9' }"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #default="{ $index }">
            <span class="font-medium text-gray-500">{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" min-width="120">
          <template #default="{ row }">
            <span class="font-mono font-semibold text-gray-800">{{
              row.licensePlate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="model" label="车辆型号" min-width="150">
          <template #default="{ row }">
            <span class="text-gray-700">{{ row.model }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="车辆状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
              class="rounded-full px-2 py-1 text-xs font-medium"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="driverName" label="所属司机" min-width="120">
          <template #default="{ row }">
            <span class="text-gray-700">{{ row.driverName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="fuelConsumption"
          label="标准油耗(L/100km)"
          width="150"
          align="center"
        >
          <template #default="{ row }">
            {{ row.fuelConsumption ? `${row.fuelConsumption}L/100km` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="80" align="center">
          <template #default="{ row }">
            <div class="flex items-center justify-center space-x-2">
              <div
                class="h-4 w-4 rounded-full border border-gray-300 bg-gradient-to-r from-gray-300 to-gray-400"
              ></div>
              <span class="text-sm text-gray-700">{{ row.color }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="purchaseDate"
          label="购买日期"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <span class="text-sm text-gray-600">{{
              row.purchaseDate || '-'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="insuranceDue"
          label="保险到期日"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <span class="text-sm text-gray-600">{{
              row.insuranceDue || '-'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="inspectionDue"
          label="年检到期日"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <span class="text-sm text-gray-600">{{
              row.inspectionDue || '-'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <div class="flex justify-center space-x-2">
              <el-button
                link
                type="primary"
                size="small"
                :icon="MdiKeyboardEsc"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                :icon="MdiKeyboardEsc"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-if="pagination.total > 0"
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="pagination.pageSizeOptions"
        :layout="'total, sizes, prev, pager, next, jumper'"
        :background="true"
        class="mt-4 flex justify-center"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>
    <!-- 新增/编辑弹框 -->
    <VehicleFormDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :data="currentVehicle"
      :is-edit="isEdit"
      @success="handleSuccess"
    />
  </div>
</template>

<style scoped>
/* 响应式优化 */
@media (max-width: 768px) {
  :deep(.el-card) {
    margin-bottom: 16px;
  }

  :deep(.vehicle-table) {
    font-size: 12px;
  }
}

:deep(.vehicle-table) {
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow:
    0 4px 6px -1px rgb(0 0 0 / 10%),
    0 2px 4px -1px rgb(0 0 0 / 6%);
}

:deep(.vehicle-table .el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
}

:deep(.vehicle-table .el-table__body-wrapper) {
  border-radius: 0 0 12px 12px;
}

:deep(.vehicle-table .el-table__row:nth-child(even)) {
  background-color: #f9fafb;
}

/* 搜索表单样式优化 */
:deep(.search-form .el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow:
    0 0 0 3px rgb(59 130 246 / 10%),
    0 2px 4px 0 rgb(0 0 0 / 5%);
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

/* 按钮样式优化 */
:deep(.el-button) {
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.2s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border: none;
  box-shadow:
    0 4px 6px -1px rgb(59 130 246 / 30%),
    0 2px 4px -1px rgb(59 130 246 / 20%);
}

/* 标签样式优化 */
:deep(.el-tag) {
  padding: 4px 12px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
}

:deep(.el-tag--success) {
  color: white;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
}

:deep(.el-tag--warning) {
  color: white;
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  border: none;
}

:deep(.el-tag--info) {
  color: white;
  background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
  border: none;
}

:deep(.el-tag--danger) {
  color: white;
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
}

/* 卡片阴影效果 */
:deep(.el-card) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

/* 表格文字样式 */
:deep(.el-table) {
  font-size: 14px;
  color: #374151;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #1f2937;
  background: #f9fafb;
}

/* 操作按钮样式 */
:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
}

/* 自定义表格样式 */
</style>
